package org.jeecg.modules.system.controller.login;

import com.zhaowl.rsa.util.RsaUtil;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.util.Base64;

/**
 * RSA 公钥/私钥 Property
 *
 * @author jiangtianyi
 * @version 1.0
 * @date 2023-03-09
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "basicplatform.rsa")
public class RsaEncryptProperty {

    private String publicKey;

    private String privateKey;

    /**
     * RSA公钥加密
     *
     * @param originalString 原始数据字符串
     * @return byte[]
     * @author jiangtianyi
     * @since 1.0
     */
    @SneakyThrows
    public byte[] encrypt(String originalString) {
        PublicKey publicKey = RsaUtil.base64PublicKeyRestore(this.getPublicKey());
        String base64 = Base64.getEncoder().encodeToString(originalString.getBytes(StandardCharsets.UTF_8));
        return RsaUtil.encryptByPublicKey(publicKey, base64);
    }

    /**
     * RSA私钥解密
     *
     * @param encryptedString RSA加密后的字符串
     * @return String
     * @author jiangtianyi
     * @since 1.0
     */
    @SneakyThrows
    public String decrypt(String encryptedString) {
        return new String(RsaUtil.decryptByPrivateKey(this.getPrivateKey(), encryptedString));
    }

}